package com.xxq.semester.service.impl.ai;

import com.xxq.semester.service.ai.VideoPollingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class VideoPollingServiceImpl implements VideoPollingService {

    @Autowired
    private JavaMailSender mailSender;
    
    @Autowired
    private RestTemplate restTemplate;
    
    // 存储轮询任务状态的内存缓存（生产环境建议使用Redis）
    private final Map<String, Map<String, Object>> taskCache = new ConcurrentHashMap<>();
    
    // API配置
    private static final String API_URL = "https://api.siliconflow.cn/v1/video/status";
    
    @Value("${ai.video.token:your-token-here}")
    private String apiToken;

    @Override
    public String startPolling(String requestId, String email) {
        String taskId = UUID.randomUUID().toString();
        
        // 保存轮询任务信息
        Map<String, Object> taskInfo = new HashMap<>();
        taskInfo.put("taskId", taskId);
        taskInfo.put("requestId", requestId);
        taskInfo.put("email", email);
        taskInfo.put("status", "POLLING");
        taskInfo.put("createTime", System.currentTimeMillis());
        taskInfo.put("lastCheckTime", null);
        taskInfo.put("checkCount", 0);
        
        taskCache.put(taskId, taskInfo);
        
        // 异步开始轮询
        startAsyncPolling(taskId);
        
        return taskId;
    }

    @Async
    public void startAsyncPolling(String taskId) {
        Map<String, Object> taskInfo = taskCache.get(taskId);
        if (taskInfo == null) {
            return;
        }
        
        String requestId = (String) taskInfo.get("requestId");
        String email = (String) taskInfo.get("email");
        
        try {
            int checkCount = 0;
            int maxChecks = 120; // 最多检查120次（1小时，每30秒检查一次）
            
            while (checkCount < maxChecks) {
                checkCount++;
                
                // 查询视频生成状态
                Map<String, Object> apiResponse = queryVideoStatus(requestId);
                
                // 更新本地任务状态
                taskInfo.put("lastCheckTime", System.currentTimeMillis());
                taskInfo.put("checkCount", checkCount);
                taskInfo.put("apiResponse", apiResponse);
                
                if (apiResponse != null) {
                    String status = (String) apiResponse.get("status");
                    
                    if ("Succeed".equalsIgnoreCase(status)) {
                        // 视频生成完成
                        taskInfo.put("status", "COMPLETED");
                        
                        // 从返回格式中解析视频URL
                        String videoUrl = extractVideoUrl(apiResponse);
                        taskInfo.put("videoUrl", videoUrl);
                        
                        // 控制台输出完成信息
                        System.out.println("=== AI视频生成完成 ===");
                        System.out.println("请求ID: " + requestId);
                        System.out.println("邮箱: " + email);
                        System.out.println("视频链接: " + videoUrl);
                        System.out.println("完整响应: " + apiResponse);
                        System.out.println("========================");
                        
                        // 发送邮件通知
                        sendCompletionEmail(email, requestId, videoUrl, apiResponse);
                        break;
                        
                    } else if ("Failed".equalsIgnoreCase(status) || "Error".equalsIgnoreCase(status)) {
                        // 视频生成失败
                        taskInfo.put("status", "FAILED");
                        
                        String errorMessage = (String) apiResponse.get("reason");
                        if (errorMessage == null) {
                            errorMessage = (String) apiResponse.get("message");
                        }
                        if (errorMessage == null) {
                            errorMessage = "视频生成失败，未知错误";
                        }
                        
                        taskInfo.put("errorMessage", errorMessage);
                        
                        // 控制台输出失败信息
                        System.out.println("=== AI视频生成失败 ===");
                        System.out.println("请求ID: " + requestId);
                        System.out.println("邮箱: " + email);
                        System.out.println("失败原因: " + errorMessage);
                        System.out.println("完整响应: " + apiResponse);
                        System.out.println("========================");
                        
                        // 发送失败通知邮件
                        sendFailureEmail(email, requestId, errorMessage);
                        break;
                    } else {
                        // 其他状态（如Processing等），继续轮询
                        System.out.println("轮询中... 请求ID: " + requestId + ", 状态: " + status + ", 第" + checkCount + "次检查");
                    }
                }
                
                // 等待30秒后再次查询
                Thread.sleep(30000);
            }
            
            // 如果达到最大检查次数仍未完成
            if (checkCount >= maxChecks && !"COMPLETED".equals(taskInfo.get("status")) 
                && !"FAILED".equals(taskInfo.get("status"))) {
                taskInfo.put("status", "TIMEOUT");
                sendTimeoutEmail(email, requestId);
            }
            
        } catch (Exception e) {
            // 轮询过程中出错
            taskInfo.put("status", "ERROR");
            taskInfo.put("errorMessage", e.getMessage());
            sendErrorEmail(email, requestId, e.getMessage());
        }
    }

    @SuppressWarnings("rawtypes")
    private Map<String, Object> queryVideoStatus(String requestId) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + apiToken);
            headers.set("Content-Type", "application/json");
            
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("requestId", requestId);
            
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            
            ResponseEntity<Map> response = restTemplate.exchange(
                API_URL,
                HttpMethod.POST,
                entity,
                Map.class
            );
            
            @SuppressWarnings("unchecked")
            Map<String, Object> result = response.getBody();
            return result;
            
        } catch (Exception e) {
            System.err.println("查询视频状态失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 从API响应中提取视频URL
     * 响应格式: {"status": "Succeed", "results": {"videos": [{"url": "..."}]}}
     */
    @SuppressWarnings("unchecked")
    private String extractVideoUrl(Map<String, Object> apiResponse) {
        try {
            Map<String, Object> results = (Map<String, Object>) apiResponse.get("results");
            if (results != null) {
                Object videosObj = results.get("videos");
                if (videosObj instanceof java.util.List) {
                    java.util.List<Map<String, Object>> videos = (java.util.List<Map<String, Object>>) videosObj;
                    if (!videos.isEmpty()) {
                        Map<String, Object> firstVideo = videos.get(0);
                        return (String) firstVideo.get("url");
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("解析视频URL失败: " + e.getMessage());
        }
        return null;
    }

    private void sendCompletionEmail(String email, String requestId, String videoUrl, Map<String, Object> apiResponse) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("1311624739@qq.com");
            message.setTo(email);
            message.setSubject("🎉 AI视频生成完成通知");
            
            String emailContent;
            if (videoUrl != null && !videoUrl.trim().isEmpty()) {
                emailContent = String.format(
                    "您好！\n\n" +
                    "🎉 恭喜！您的AI视频生成任务已完成。\n\n" +
                    "📋 请求ID：%s\n" +
                    "🎬 视频链接：%s\n\n" +
                    "请点击上方链接查看和下载您的视频。\n\n" +
                    "📊 详细信息：\n%s\n\n" +
                    "如有任何问题，请联系我们。\n\n" +
                    "谢谢使用我们的服务！",
                    requestId, 
                    videoUrl,
                    formatApiResponse(apiResponse)
                );
            } else {
                emailContent = String.format(
                    "您好！\n\n" +
                    "您的AI视频生成任务已完成，但未能获取到视频链接。\n\n" +
                    "📋 请求ID：%s\n\n" +
                    "📊 完整响应信息：\n%s\n\n" +
                    "请联系技术支持获取帮助。\n\n" +
                    "谢谢！",
                    requestId, 
                    apiResponse.toString()
                );
            }
            
            message.setText(emailContent);
            mailSender.send(message);
            
        } catch (Exception e) {
            System.err.println("发送完成邮件失败: " + e.getMessage());
        }
    }

    /**
     * 格式化API响应信息，让邮件更易读
     */
    @SuppressWarnings("unchecked")
    private String formatApiResponse(Map<String, Object> apiResponse) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("状态: ").append(apiResponse.get("status")).append("\n");
            
            Map<String, Object> results = (Map<String, Object>) apiResponse.get("results");
            if (results != null) {
                Object timings = results.get("timings");
                Object seed = results.get("seed");
                if (timings != null) {
                    sb.append("生成耗时: ").append(timings).append("\n");
                }
                if (seed != null) {
                    sb.append("随机种子: ").append(seed).append("\n");
                }
            }
            
            return sb.toString();
        } catch (Exception e) {
            return apiResponse.toString();
        }
    }

    private void sendFailureEmail(String email, String requestId, String errorMessage) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("1311624739@qq.com");
            message.setTo(email);
            message.setSubject("AI视频生成失败通知");
            message.setText(String.format(
                "您好！\n\n" +
                "很抱歉，您的AI视频生成任务失败了。\n\n" +
                "请求ID：%s\n" +
                "失败原因：%s\n\n" +
                "请检查参数后重新提交。\n\n" +
                "谢谢！",
                requestId, errorMessage
            ));
            
            mailSender.send(message);
            
        } catch (Exception e) {
            System.err.println("发送失败邮件失败: " + e.getMessage());
        }
    }

    private void sendTimeoutEmail(String email, String requestId) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("1311624739@qq.com");
            message.setTo(email);
            message.setSubject("AI视频生成超时通知");
            message.setText(String.format(
                "您好！\n\n" +
                "您的AI视频生成任务轮询超时（已轮询1小时）。\n\n" +
                "请求ID：%s\n\n" +
                "请稍后手动查看生成状态或重新提交任务。\n\n" +
                "谢谢！",
                requestId
            ));
            
            mailSender.send(message);
            
        } catch (Exception e) {
            System.err.println("发送超时邮件失败: " + e.getMessage());
        }
    }

    private void sendErrorEmail(String email, String requestId, String errorMessage) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("1311624739@qq.com");
            message.setTo(email);
            message.setSubject("AI视频轮询服务异常通知");
            message.setText(String.format(
                "您好！\n\n" +
                "轮询您的AI视频生成任务时发生异常。\n\n" +
                "请求ID：%s\n" +
                "异常信息：%s\n\n" +
                "请联系管理员或重新提交任务。\n\n" +
                "谢谢！",
                requestId, errorMessage
            ));
            
            mailSender.send(message);
            
        } catch (Exception e) {
            System.err.println("发送异常邮件失败: " + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getTaskStatus(String taskId) {
        Map<String, Object> taskInfo = taskCache.get(taskId);
        if (taskInfo == null) {
            throw new RuntimeException("轮询任务不存在");
        }
        return new HashMap<>(taskInfo); // 返回副本，避免外部修改
    }
}
